package com.ivr.cm.handler.impl;

import java.text.SimpleDateFormat;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Queue;

import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.log4j.Logger;

import com.ivr.cm.cache.impl.ConfigBusinessCache;
import com.ivr.cm.cache.impl.ConfigFilterCache;
import com.ivr.cm.cache.impl.ConfigRouterCache;
import com.ivr.cm.cache.impl.SelfFilterCache;
import com.ivr.cm.data.BaseData;
import com.ivr.cm.handler.BaseHandler;
import com.ivr.cm.msg.HttpMsg;
import com.ivr.cm.service.impl.DbService;
import com.ivr.cm.service.impl.FilterServiceImpl;
import com.ivr.cm.util.SpringServiceUtil;
import com.ivr.cm.vo.UserBehaviorVo;
import com.ivr.cm.vo.UserHangVo;
import com.ivr.cm.vo.LimitFeeVo;
import com.ivr.cm.vo.LimitUserVo;
import com.ivr.cm.vo.SelfFilterVo;
import com.ivr.cm.vo.ConfigBusinessVo;
import com.ivr.cm.vo.ConfigFilterVo;
import com.ivr.cm.vo.UserBillVo;
import com.ivr.cm.vo.ConfigRouterVo;

public class CommonUserBillHandler extends BaseHandler {
	private static Logger logger = Logger.getLogger(CommonUserBillHandler.class);
	private List<Integer> self_thres_hold = new ArrayList<Integer>();
	
	public CommonUserBillHandler() {
		self_thres_hold.add(48);
		self_thres_hold.add(12);
//		self_thres_hold.add(24);
		self_thres_hold.add(68);
//		self_thres_hold.add(95);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected String action(BaseData baseData) {
		try{
			logger.info(String.format("[%s][%s]保存账单开始", baseData.getCalling(), baseData.getLong_called()));
			
			String[] tmp = baseData.getBody().split("\\|");
			if(tmp.length >= 4){
				
				/**从缓存中获得SP号码的业务配置信息*/
				ConfigBusinessCache configBusinessCache = (ConfigBusinessCache) SpringServiceUtil.getService("configBusinessCache");
				AbstractMap<String, ConfigBusinessVo> configBusinessMap = (AbstractMap<String, ConfigBusinessVo>) configBusinessCache.getCache();
				ConfigBusinessVo configBusinessVo = configBusinessMap.get(baseData.getShort_called());
				
				/**账单VO保存用户账单*/
				UserBillVo userBillVo = new UserBillVo();
				userBillVo.setMobile(tmp[0]);
				userBillVo.setSp_number(tmp[1]);
				userBillVo.setProvince(baseData.getProvince());
				userBillVo.setCity(baseData.getCity());
				userBillVo.setTime_begin(tmp[2]);
				userBillVo.setTime_end(tmp[3]);
				userBillVo.setLinkId(baseData.getLinkId());
				
				/**获得路由信息*/
				ConfigRouterCache configRouterCache = (ConfigRouterCache) SpringServiceUtil.getService("configRouterCache");
				AbstractMap<String, ConfigRouterVo> configRouterMap = (AbstractMap<String, ConfigRouterVo>) configRouterCache.getCache();
				ConfigRouterVo configRouterVo = configRouterMap.get(baseData.getLong_called());
				if(configRouterVo != null){
					userBillVo.setLower_id(configRouterVo.getLower_id());
					userBillVo.setRouter_id(configRouterVo.getId());
				}else{
					userBillVo.setLower_id(0);
					userBillVo.setRouter_id(0);
				}
				
				/**IVR计费数据VO保存用户计费信息*/
				LimitFeeVo limitFeeVo = new LimitFeeVo();
				limitFeeVo.setMobile(tmp[0]);
				limitFeeVo.setProvince(baseData.getProvince());
				limitFeeVo.setCity(baseData.getCity());
				limitFeeVo.setSp_code(baseData.getShort_called());
				limitFeeVo.setTime_begin(tmp[2]);
				limitFeeVo.setTime_end(tmp[3]);
				limitFeeVo.setLinkId(baseData.getLinkId());
				
				SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				long begin = format.parse(limitFeeVo.getTime_begin()).getTime();//计费开始时间
				long end = format.parse(limitFeeVo.getTime_end()).getTime();	//计费结束时间
				long seconds = Math.abs(end - begin)/1000;		// 实际拨打时长 单位秒
				long feeMinute = seconds / 60;						// 计算计费分钟数 不足60秒的也按一分钟计算
				if(seconds % 60 > 0) {
					feeMinute++;
				}
				
				userBillVo.setSecond(Integer.parseInt(String.valueOf(seconds)));
				userBillVo.setMinute(Integer.parseInt(String.valueOf(feeMinute)));
				limitFeeVo.setFee_minute(Integer.parseInt(String.valueOf(feeMinute)));
				/**获得业务的计费方式*/
				int fee_type = configBusinessVo.getFee_type();
				if(fee_type == 1){
					int fee_code = configBusinessVo.getFee_code();
					int feeMoney = Integer.parseInt(String.valueOf(feeMinute)) * fee_code;
					
					userBillVo.setFee_number(feeMoney);
					limitFeeVo.setFee_money(feeMoney);
				}else if(fee_type == 2){
					int fee_code = configBusinessVo.getFee_code();
					
					userBillVo.setFee_number(fee_code);
					limitFeeVo.setFee_money(fee_code);
				}
				
//				logger.info(String.format("重新计算要不要过滤，linkid为[%s]", userBillVo.getLinkId()));
//				int isFilter = 0;
//				if( userBillVo.getFee_number() >= 1500)
//				{
//					SelfFilterCache selfFilterCache = (SelfFilterCache)SpringServiceUtil.getService("selfFilterCache");
//					AbstractMap<String, SelfFilterVo> selfFilterMap = (AbstractMap<String, SelfFilterVo>) selfFilterCache.getCache();
//					
//					SelfFilterVo selfFilterVo = selfFilterMap.get(configRouterVo.getSp_number());
//					int self_thres_index = selfFilterVo.getSelf_thres_index() + 1;
//					selfFilterVo.setSelf_thres_index(self_thres_index);
//					for (int i = 0; i < self_thres_hold.size(); i ++) {
//						if(self_thres_hold.get(i) == self_thres_index) {
//							logger.info(String.format("自消费拨打计费超过15元，再次进行扣量计算，序列数为[%s]完成匹配！", self_thres_index));
//							isFilter = 1;
//						}
//					}
//				}
//				
//				logger.info(String.format("按原过滤属性执行，号码为[%s]，过滤属性[%d]", userBillVo.getMobile(), isFilter));
//				userBillVo.setIsfilter(isFilter);
				
				/**设置当前日和月*/
				SimpleDateFormat formatorForNow = new SimpleDateFormat("yyyyMMdd");
				Calendar calendar = Calendar.getInstance();
				String feeDay = formatorForNow.format(calendar.getTime());
				String feeMonth = feeDay.substring(0, 6);
				limitFeeVo.setFee_day(feeDay);
				limitFeeVo.setFee_month(feeMonth);
				
				/**话单未被过滤  把信息新增到转发表*/
				if(userBillVo.getIsfilter() != 1){
					
					/* 因为对客户号码限制，已经隐去号码的末4位，无法在对单一号码进行限制，去除对单一号码的日月限制 */
					Queue<HttpMsg> dispatchQueue = (Queue<HttpMsg>) SpringServiceUtil.getService("dispatchQueue");
					dispatchQueue.add(userBillVo);
				}
				
				/**保存到用户挂机表*/
				UserHangVo userHangVo = new UserHangVo();
				userHangVo.setMobile(tmp[0]);
				userHangVo.setSp_number(tmp[1]);
				userHangVo.setLinkId(baseData.getLinkId());
				
				/**保存用户行为到行为表， -1 标识用户已挂机*/
				UserBehaviorVo userBehaviorVo = new UserBehaviorVo();
				userBehaviorVo.setMobile(baseData.getCalling());
				userBehaviorVo.setSp_number(baseData.getLong_called());
				userBehaviorVo.setProvince(baseData.getProvince());
				userBehaviorVo.setCity(baseData.getCity());
				userBehaviorVo.setPressed("-1");
				
				DbService dbService = (DbService) SpringServiceUtil.getService("dbService");
				dbService.doProcess(userBillVo);
				dbService.doProcess(userHangVo);
				dbService.doProcess(limitFeeVo);
				dbService.doProcess(userBehaviorVo);
			}else{
				logger.info(String.format("[%s][%s]参数传入有误", baseData.getCalling(),baseData.getLong_called()));
			}
		}catch (Exception e) {
			logger.error(String.format("[%s][%s]话单入库异常:%s",baseData.getCalling(),baseData.getLong_called(),ExceptionUtils.getFullStackTrace(e)));
		}
		return "";
	}
}